package com.muse.app.service;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.muse.constant.RedisKey;
import com.muse.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import redis.clients.jedis.JedisCluster;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * Created with IntelliJ IDEA.
 * User: lee
 * Date: 2021/4/20
 * Time: 3:41 下午
 * Description:
 */
@Service
@Slf4j
public class SmsService {
    private static final String SMS_SIGN = "MissKing美业";
    private static final String SMS_LOGIN_TEMPLATE = "SMS_215344297";
    private static final String SMS_UPDATE_PHONE_TEMPLATE = "SMS_216836650";


    @Value("${ali.accessKey.Id}")
    private String aliAccessKey;

    @Value("${ali.accessKey.secret}")
    private String aliAccessKeySecret;

    @Autowired
    private StringRedisTemplate redisTemplate;


    public void sendSmsCode(String phone, Integer type) throws Exception {
        int code = (int) ((Math.random() * 9 + 1) * 1000);
        Map<String, Object> templateParam = new HashMap<>(1);
        templateParam.put("code", code);

        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", aliAccessKey, aliAccessKeySecret);
        IAcsClient client = new DefaultAcsClient(profile);
        SendSmsRequest request = new SendSmsRequest();
        request.setSysMethod(MethodType.POST);
        request.setPhoneNumbers(phone);
        request.setSignName(SMS_SIGN);
        String redisKey;
        if (type == 1) {
            request.setTemplateCode(SMS_LOGIN_TEMPLATE);
            redisKey = RedisKey.SMS_CODE_LOGIN + phone;
        } else {
            request.setTemplateCode(SMS_UPDATE_PHONE_TEMPLATE);
            redisKey = RedisKey.SMS_CODE_UPDATE_PHONE + phone;
        }
        request.setTemplateParam(JsonUtils.toJson(templateParam));

        SendSmsResponse response = client.getAcsResponse(request);
        if (response.getCode().equals("OK")) {
            redisTemplate.opsForValue().set(redisKey, String.valueOf(code), 3, TimeUnit.MINUTES);
//            jedis.setex(redisKey, 300, String.valueOf(code));
        } else {
            throw new Exception(response.getMessage());
        }
    }
}
